//
//  ZWPropertyPayController.m
//  NewProject
//
//  Created by tongtong on 2018/5/19.
//  Copyright © 2018年 chenIos. All rights reserved.
//

#import "ZWPropertyPayController.h"
#import "ZScanController.h"
@interface ZWPropertyPayController ()
@property (nonatomic,strong) UITextField *addressField;
@property (nonatomic,strong) UITextField *numField;
@property (nonatomic,strong) UITextField *describField;
@property(nonatomic,assign)BOOL  reload;

@end

@implementation ZWPropertyPayController
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    
}
- (void)setupNav{
    UIButton *scanbtn = [[UIButton alloc]init];
    scanbtn.frame = CGRectMake(Scare_Width(10), Scare_Width(25), 44, 44);
    [scanbtn setImage:[UIImage imageNamed:@"scan"] forState:UIControlStateNormal];
    [scanbtn setTitleColor:COLOR_MIDDLE_GRAY forState:UIControlStateNormal];
    [scanbtn setTintColor:COLOR_MIDDLE_GRAY];
    [scanbtn addTarget:self action:@selector(scanFliter) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanbtn];
    [scanbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-Scare_Width(10));
        make.top.mas_equalTo(Scare_Width(25));
        make.height.mas_equalTo(44);
    }];
//    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc]initWithTitle:@"扫一扫" style:(UIBarButtonItemStylePlain) target:self action:@selector(scanFliter)];
}
- (void)scanFliter{
    ZScanController *sanVC = [ZScanController new];
    __weak typeof(self.addressField) weakAddress = self.addressField;
    sanVC.scanResult = ^(NSString *address) {
        weakAddress.text = address;
    };
    [self presentViewController:sanVC animated:YES completion:nil];
//    [self.navigationController pushViewController:sanVC animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_WHITE;
    UIButton *btn = [[UIButton alloc]init];
    btn.frame = CGRectMake(Scare_Width(10), Scare_Width(25), 44, 44);
    [btn setImage:[[UIImage imageNamed:@"back_close"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [btn setTintColor:COLOR_MIDDLE_GRAY];
    [btn addTarget:self action:@selector(gotoback) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

    UILabel *lab = [[UILabel alloc]init];
    lab.frame = CGRectMake(100, Scare_Width(40), SCREEN_W - 200, Scare_Width(25));
    lab.font = H2;
    lab.textColor = COLOR_NAV_TITLE;
    lab.text =  [NSString stringWithFormat:@"%@ %@",self.curreny, Z_Location(@"send")];
    lab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lab];
    
    for (int i = 0; i < 3; i ++) {
        UIView *lineView = [[UIView alloc]init];
        lineView.frame = CGRectMake(Scare_Width(15), Scare_Width(75) +Scare_Width(82)*i, SCREEN_W - Scare_Width(30), 0.5);
        lineView.backgroundColor = COLOR_LIGHT_GRAY;
        [self.view addSubview:lineView];
    }
    
    NSArray *arry = @[Z_Location(@"receiveAddress"),Z_Location(@"amount"),Z_Location(@"memo")];
    
    for (int j = 0; j <2; j++) {
        UITextField *textField = [[UITextField alloc]init];
        textField.frame = CGRectMake(Scare_Width(15), Scare_Width(117) +Scare_Width(82)*j, SCREEN_W - Scare_Width(30), Scare_Width(30));
        textField.textColor = [UIColor colorWithHexString:@"#cccccc"];
        textField.font = H_Medium4;
        textField.placeholder = arry[j];
        if (j == 0) {
            self.addressField = textField;
        }else if (j == 1){
            textField.keyboardType = UIKeyboardTypeDecimalPad;
            self.numField = textField;
            
        }else{
            self.describField = textField;
        }
        [self.view addSubview:textField];
    }
    UIButton *copyBtn = [[UIButton alloc]init];
    CGFloat bottom = iPhoneX ? 34 : 0;
    copyBtn.frame =  CGRectMake(Scare_Width(20), SCREEN_H - Scare_Width(60) - bottom, SCREEN_W - Scare_Width(40), Scare_Width(50));
    [copyBtn setTitle:Z_Location(@"next") forState:UIControlStateNormal];
    [copyBtn addTarget:self action:@selector(nextStyleMethod) forControlEvents:UIControlEventTouchUpInside];
    copyBtn.titleLabel.font = H_Medium3;
    [copyBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
    [copyBtn setBackgroundColor:COLOR_BLUE];
    [self.view addSubview:copyBtn];
    [self setupNav];



}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_addressField resignFirstResponder];
    [_numField resignFirstResponder];
    [_describField resignFirstResponder];

}
#pragma mark  -- 下一步---
-(void)nextStyleMethod{
    if (self.reload) {
        return;
    }
    if (ZWSTRING_ISEMPTY(_addressField.text)) {
        [self.view makeToast:Z_Location(@"inputAddress") duration:2.0f position:CSToastPositionCenter];
        return;
    }
    if (ZWSTRING_ISEMPTY(_numField.text)) {
        [self.view makeToast:Z_Location(@"inputAmount") duration:2.0f position:CSToastPositionCenter];
        return;
    }
    if (![self validateMoney:self.numField.text]) {
        [ZProgressManager showError:Z_Location(@"point_input_max_lenght")];
        ZWLog(@"xxxxxx");
        return;
    }
    ZWWeakSelf;
    NSString * amount =  weakSelf.numField.text;

    //验证地址
    WewalletsdkExecuteResult *result = [ZGRPC_Manager verifyAddress:_addressField.text];
    if (result.success) {
        //转账
        NSString *from = self.walletInfo.walletAdress;
        NSString *to = self.addressField.text;
        NSString *message  = self.curreny;
        NSString *str = [NSString stringWithFormat:@"from=%@&to=%@&amount=%@&currency=%@",from,to,amount,message];
        
        NSString *key =  self.walletInfo.privateKey;
        WewalletsdkWeWallet *wallet = [ZGRPC_Manager importPrivatekey:key];
        NSString  *sign =  [ZGRPC_Manager getSign:str key:wallet.privateKey];
        NSString *url = [NSString stringWithFormat:@"%@wallet/transfer",PortServer];
        NSDictionary *param = @{
                                @"from":from,
                                @"to":to,
                                @"amount":amount,
                                @"currency":message,
                                @"signature":sign,
                                @"publicKey":wallet.publicKey,
                                };
        ZWLog(@"url = %@\nparam = %@",url,param);
        self.reload = YES;
        [ZProgressManager show];
        [ZNetManager POST:url parameters:param success:^(NSURLSessionDataTask *task, id  _Nullable responseObject) {
            weakSelf.reload = NO;
            ZWLog(@"responseObject = %@",responseObject);
            NSInteger status = [responseObject[@"status"] integerValue];
            if(status == 1){
                [ZProgressManager showSuccess:responseObject[@"message"]];
                [weakSelf dismissViewControllerAnimated:YES completion:nil] ;
            }else
            {
                [ZProgressManager showError:responseObject[@"message"]];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            weakSelf.reload = NO;
            [ZProgressManager showError:@"连接失败"];
            ZWLog(@"error = %@",error.userInfo);
        }];
    }else
    {
        [self.view makeToast:result.info duration:2.0f position:CSToastPositionCenter];
    }
    
        
    
 
}


-(BOOL)validateMoney:(NSString *)money
{
    NSString *phoneRegex = @"^[0-9]+(\\.[0-9]{1,8})?$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:money];
}
-(void)gotoback{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
